// Learn cc.Class:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/class.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/class.html
// Learn Attribute:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/life-cycle-callbacks.html

cc.TimerTo = cc.Class({
    name: 'cc.TimerTo',
    extends: cc.ActionInterval,

    ctor:function (duration, time) {
        this._startTime = 0;
        this._endTime = 0;
        this._deltaTime = 0;
        time !== undefined && cc.TimerTo.prototype.initWithDuration.call(this, duration, time);
    },

    /*
     * Initializes the action.
     * @param {Number} duration
     * @param {Number} progress
     * @return {Boolean}
     */
    initWithDuration:function (duration, time) { //function overload here
        if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) {
            this._endTime = time;
            return true;
        }
        return false;
    },

    clone:function () {
        var action = new cc.TimerTo();
        this._cloneDecoration(action);
        action.initWithDuration(this._duration, this._endTime);
        return action;
    },

    startWithTarget:function (target) {
        cc.ActionInterval.prototype.startWithTarget.call(this, target);

        var com = target.getComponent(cc.Label);
        if (com) {
            this._startTime = this.parseTime(com.string);
        }
        this._deltaTime = this._endTime - this._startTime;
    },

    update:function (dt) {
        dt = this._computeEaseTime(dt);
        if (this.target) {
            var com = this.target.getComponent(cc.Label);
            if (com) {
                com.string = this.formatTime(Math.ceil(this._startTime + this._deltaTime * dt));
            } 
        }
    },

    parseTime: function (timeString) {
        let arr = timeString.split(":")
        return parseInt(arr[0])*60 + parseInt(arr[1])
    },

    formatTime: function (time) {
        let H = Math.floor(time / 3600)
        let M = Math.floor(time / 60) - H * 60
        let S = time - H * 60 * 60 - M * 60
        //let h = H < 10 ? '0'+H+ ':' : H+ ':';
        let m = M < 10 ? '0'+M+ ':' : M+ ':';
        let s = S< 10 ? '0'+S : S;
        return m+s;
    }
});

cc.timerTo = function (duration, time) { //function overload
    return new cc.TimerTo(duration, time);
};
